import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '@/views/MainBox.vue'
import RoutesConfig from './config'
import store from '@/store'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/mainbox',
    name: 'mainbox',
    component: MainBox

    // mainbox的嵌套路由，后面根据权限动态添加
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const ConfigRoutes = () => {
  if (!router.hasRoute('mainbox')) {
    router.addRoute({
      path: '/mainbox',
      name: 'mainbox',
      component: MainBox
    })
  }

  RoutesConfig.forEach((item) => {
    checkoutPermission(item) && router.addRoute('mainbox', item)
  })

  store.commit('changeGetterRouter', true)
}
const checkoutPermission = (item) => {
  if (item.reqiureAdmin) {
    return store.state.userInfo.role === 1 //false
  }
  return true
}

// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    // 如果已经授权，则放行 next()
    // 未授权，重定向到login
    if (!localStorage.getItem('token')) {
      next({ path: '/login' })
    } else {
      // 第一次
      if (!store.state.isGetterRouter) {
        // 先删除所有的嵌套路由，再重新配置
        router.removeRoute('mainbox')
        ConfigRoutes()
        next({
          path: to.fullPath
        })
      } else {
        next()
      }
    }
  }
})

export default router
